package org.boge.sharpdoc.controller;

import org.apache.commons.io.FileUtils;
import org.boge.sharpdoc.config.Settings;
import org.boge.sharpdoc.util.CheckCodePicture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("picture")
public class PictureController {
    @Autowired
    private Settings settings;
    @Autowired
    private HttpSession session;

    @GetMapping("getAvatar")
    public byte[] getAvatar(String fileName) throws IOException {
        File avatarFile;
        if (fileName.equals("null"))
            avatarFile = ResourceUtils.getFile("classpath:static/imgs/avatars/default_avatar.jpg");
        else
            avatarFile = new File(settings.getAvatarsDir(), fileName);
        if (avatarFile.exists())
            return FileUtils.readFileToByteArray(avatarFile);
        else
            return null;
    }

    @GetMapping("getBanner")
    public byte[] getBanner(String fileName) throws IOException {
        File avatarFile = new File(settings.getBannersDir(), fileName);
        if (avatarFile.exists())
            return FileUtils.readFileToByteArray(avatarFile);
        else
            return null;
    }

    @GetMapping("getIcon")
    public byte[] getIcon(String fileName) throws IOException {
        File avatarFile = new File(settings.getIconsDir(), fileName);
        if (avatarFile.exists())
            return FileUtils.readFileToByteArray(avatarFile);
        else
            return null;
    }

    @GetMapping("checkCodeImg")
    public void checkCodeImg(HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        CheckCodePicture codePicture = new CheckCodePicture();
        session.setAttribute("checkCodeImg", codePicture.getCode());
        codePicture.write(response.getOutputStream());
    }
}